<template>
  <div class="pui-search">
    <pui-popper theme="light" @onClose="clickOutsideHandle" @onOpen="toggleOpen" :placement="placement" :disabled="disabled">
      <pui-input
        v-model="props.modelValue"
        :iconPosition="iconPosition"
        :type="type"
        :size="size"
        :clearAble="clearAble"
        @onClear="clearModelValue"
        @onInput="onInputHandle"
        @onIconClick="onIconClick"
      >
      </pui-input>
      <template #popper>
        <div class="pui-search-content">
          <div class="pui-search-content_list">
            <div
              :class="['pui-search-content_item', typeof modelValue !== 'string' && modelValue.value === item?.value && 'active-item']"
              v-for="item in filterList"
              :key="item.value"
              @click.stop="onSelectHandle(item)"
            >
              {{ item.label }}
            </div>
            <div class="no-data" v-if="filterList.length === 0">-- 无数据 --</div>
          </div>
        </div>
      </template>
    </pui-popper>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'pui-search',
});
</script>

<script lang="ts" setup>
import { reactive, watch, computed } from 'vue';
import type { Data, Props } from './interface';

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  size: 'normal',
  placement: 'bottom',
  type: 'select',
  iconPosition: 'iconPosition',
  disabled: false,
  clearAble: true,
});

const emits = defineEmits<{
  'update:modelValue': [val: any];
  onIconClick: [val: string];
}>();

const componentRef = reactive({
  isShow: false,
  keywords: '',
  showPopper: false,
  filterList: props.dataList,
});

const filterList = computed(() => {
  if (props.dataList) {
    return props.dataList;
  }
  return [];
});
const onSelectHandle = (data: Data) => {
  componentRef.keywords = data.label;
  componentRef.filterList = props.dataList.filter((item) => {
    item?.label.indexOf(componentRef.keywords) > -1;
  });
  emits('update:modelValue', data);
};

const clickOutsideHandle = () => {
  componentRef.isShow = false;
};

const toggleOpen = () => {
  componentRef.filterList = props.dataList.filter((item) => {
    item?.label.indexOf(componentRef.keywords) > -1;
  });
  componentRef.isShow = !componentRef.isShow;
};

const clearModelValue = () => {
  componentRef.keywords = '';
  componentRef.filterList = props.dataList.filter((item) => {
    item?.label.indexOf(componentRef.keywords) > -1;
  });
  emits('update:modelValue', '');
};

const onInputHandle = (e: any) => {
  componentRef.isShow = true;
  componentRef.filterList = props.dataList.filter((item) => {
    item.label.indexOf(componentRef.keywords) !== -1;
    componentRef.showPopper = componentRef.keywords !== '';
  });
  emits('update:modelValue', e.target.value);
};
const onIconClick = () => {
  emits('onIconClick', componentRef.keywords);
};
</script>
